package com.bjpowernode.micrpaykq.util;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * @description:
 * @author: pandeng_zhu
 * @time: 2022/12/22 16:00
 */
@Component
public class OrderIdUtil {

    private static final long BEGIN_TIMEsTAMP =1640995200L;

    private  static final int COUNT_BITS = 32;

    private StringRedisTemplate stringRedisTemplate;

    public OrderIdUtil(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public long generateId(String keyPrefix){
        //1.生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timeStamp = nowSecond-BEGIN_TIMEsTAMP;
        //2.生成序列号
        //获取当前日期
        String date = now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"));
        long count= stringRedisTemplate.opsForValue().increment(keyPrefix+":"+date);
        //3.拼接字符串
        // 时间戳左移32位，然后 或 序列号，有1为1
        long ids = timeStamp<<COUNT_BITS|count;
        return ids;
    }
}
